import {app,BrowserWindow,Tray,nativeImage,Menu} from 'electron';
import path from "path";

const electron = require('electron')
const ipc = electron.ipcMain

function createWindow(){
    const win = new BrowserWindow({
        frame: false,
        title:'wechat',
        icon: path.join(__dirname, '../src/assets/icon/icon.ico'),
        webPreferences: {
            contextIsolation: false,
            nodeIntegration: true,
            preload:path.join(__dirname, "./preload.js"),
            autoHideMenuBar: true,
            show: false,
        }
    })

    const trayIconPath = path.join(__dirname,"../src/assets/icon/icon.ico")
    const tray = new Tray(nativeImage.createFromPath(trayIconPath));

    const trayMenuTemplate = [
        {
            label: '退出wechat',
            click: function () {
                app.quit();
                app.quit();//因为程序设定关闭为最小化，所以调用两次关闭，防止最大化时一次不能关闭的情况
            }
        }
    ]

    tray.setContextMenu(Menu.buildFromTemplate(trayMenuTemplate));
    win.webContents.openDevTools()

    tray.on("click",function (){
        console.log("Tray con clicked")
    })

    if (process.env.NODE_ENV !== "development") {
        win.loadFile(path.join(__dirname, "./index.html"))
        // win.webContents.openDevTools()
    }else {
        let url = "http://localhost:5173"
        win.loadURL(url)
        // win.webContents.openDevTools()
    }

    ipc.on('window-close',function (){
        win.close()
    })

    ipc.on('window-min',function (){
        win.minimize()
    })
    ipc.on('window-max',function (){
        if (win.isMaximized()){
            win.restore()
        }else {
            win.maximize()
        }
    })
}

app.whenReady().then(function () {
    createWindow()
    app.on("activate",function (){
        if (BrowserWindow.getAllWindows().length == 0){
            createWindow()
        }
    })
})

app.on("window-all-closed", function (){
    if (process.platform !== "darwin") {
        app.quit()
    }
})